import {EntityMgr} from "../game/EntityManager";
import {BaseGameEntity as Entity} from "../game/BaseGameEntity";
import {Telegram} from "./Telegram";
import {Singleton} from "../misc/Singleton";


const LogStyle = [
    'color:white',
    'background-color:red',
].join(';');

function log(info:string) {
    console.log(`%c${info}`, LogStyle);
}


export class MessageDispatcher extends Singleton {

    //this method is utilized by DispatchMessage or DispatchDelayedMessages.
    //This method calls the message handling member function of the receiving
    //entity, pReceiver, with the newly created telegram
    private discharge(entity:Entity, t:Telegram) {
        if(!entity.handleMessage(t)) {
            //telegram could not be handled
            log("Message not handled");
        }
    }

    // private delayEmit(t:Telegram) {
    //     let receiver = EntityMgr.getEntityFromID(t.receiver);

    //     log(`Queued telegram ready for dispatch: Sent to ${t.receiver}. Msg is ${t.msg}`);

    //     this.discharge(receiver, t);
    // }

    dispatchMessage(delay:number, senderId:number, receiverId:number, msg:number, extra?:any) {
        let sender = EntityMgr.getEntityFromID(senderId);
        let receiver = EntityMgr.getEntityFromID(receiverId);

        //make sure the receiver is valid
        if(!receiver) {
            log(`Warning! No Receiver with ID of ${receiverId} found`);
            return;
        }

        let t = new Telegram(0, senderId, receiverId, msg, extra);

        //if there is no delay, route telegram immediately
        if(delay <= 0) {
            this.discharge(receiver, t);
        }
        else {
            log(`Delayed telegram from ${sender.id} recorded at time ${Date.now()} for ${receiver.id}. Msg is ${msg}`);
            // cc.director.getScheduler().schedule(this.delayEmit.bind(this, t), this, 0, 0, delay);

            // window.setTimeout(this.delayEmit.bind(this), delay, t);

            let delayCall = (t:Telegram) =>  {
                let receiver = EntityMgr.getEntityFromID(t.receiver);

                log(`Queued telegram ready for dispatch: Sent to ${t.receiver}. Msg is ${t.msg}`);

                this.discharge(receiver, t);
            }
            window.setTimeout(delayCall.bind(this), delay, t);
        }
    }
}

export const SEND_MSG_IMMEDIATELY = 0.0;
export const NO_ADDITIONAL_INFO   = 0;
export const SENDER_ID_IRRELEVANT = -1;

export const Dispatcher = MessageDispatcher.instance;
// export default Dispatcher;